﻿#include "CBaseDevice.h"
#include <QDebug>
CBaseDevice::CBaseDevice(const QString & name, const QString & sId, const QString & sConfig,CBaseNode * parent)
	: CBaseNode(sId,name,sConfig,parent)
{
	m_pDevice = nullptr;
	m_eNodeType = enDevice;
	((CBaseNode *)parent)->addChild(this);
	QStringList sList = sConfig.split("-");
	if (sList.size() > 0)
	{
		m_sDllName = sList[0];
	}
	if (sList.size() > 1)
	{
		m_sDeviceType = sList[1];
	}
}

CBaseDevice::~CBaseDevice() 
{
	if (m_pDevice != nullptr)
	{
		delete m_pDevice;
		m_pDevice = nullptr;
	}
	for (auto it = m_mapInputPoint.begin(); it != m_mapInputPoint.end(); it++)
	{
		it.value()->deleteAssociated((CBaseNode*)this);
	}
}

void CBaseDevice::start() 
{
	m_pDevice->startDevice();
}

void CBaseDevice::stop() 
{
	m_pDevice->stopDevice();
}

void CBaseDevice::updateData() {
	
}

void CBaseDevice::init()
{
	if (m_pDevice == nullptr)
	{
		return;
}
	QMap<QString, QString> mapPointList = m_pDevice->getInputPointList();
	for (auto it = mapPointList.begin(); it != mapPointList.end(); it++)
	{
		CBaseNode *pNode= findNodeByAddr(it.value());
		if (pNode != NULL)
		{
			if (pNode->getType() == enMeasurePoint)
			{
				m_mapInputPoint.insert(it.key(), (CMeasurePoint*)pNode);
			}
		}	
	}
	m_pDevice->setInputPointList(m_mapInputPoint);
	for (auto it = m_mapInputPoint.begin(); it != m_mapInputPoint.end(); it++)
	{
		it.value()->addAssociated((CBaseNode*)this);
	}
}

void CBaseDevice::disposeNode(CBaseNode* pNode)
{
	for (auto it = m_mapInputPoint.begin(); it != m_mapInputPoint.end(); it++)
	{
		if (it.value()->getId() == pNode->getId())
		{
			QString sKey = it.key();
			m_mapInputPoint.remove(sKey);
			m_pDevice->setInputPointList(m_mapInputPoint);
			break;
		}
	}
}

void CBaseDevice::deleteNode()
{
	//在父节点里面删除
	m_pParent->removeChild(this);
	//删除设备
	m_pDevice->deleteDevice();
    //删除子节点
	for (int i= m_pVecChildren.size()-1; i>=0; i--)
	{
		m_pVecChildren[i]->deleteNode();
	}
	delete this;
}


bool CBaseDevice::control(const QString& command, const QVariant& param) 
{
	return true;
}

void CBaseDevice::setDevice(IDevice * pDevice)
{
	m_pDevice = pDevice;
	if (m_pDevice == nullptr)
	{
		return;
	}
	QList<CMeasurePoint *>vecMeasurePoint = m_pDevice->getMeasurePoints();
	for (int i = 0; i < vecMeasurePoint.size(); i++)
	{
		addChild(vecMeasurePoint[i]);
	}
}

IDevice * CBaseDevice::getDevice()
{
	return m_pDevice;
}

QString CBaseDevice::getDllName()
{
	return m_sDllName;
}

int CBaseDevice::getDeviceType()
{
	return m_sDeviceType.toInt();
}


